<?php
namespace app\middleware;

use Illuminate\Database\Capsule\Manager as DB;

abstract class Middleware
{

    /**
     * @api 中间件处理程序
     */
    public abstract function handle($postData);

    /**
     * @api 前端验证登陆标记cookie是否合法
     */
    protected function checkCookie()
    {
        $auth = new \Auth(_CookieKey_);
        if (!$auth->isLogin()) {
            throw new \Exception('未登陆.', 401);
        } else {
            return $auth;
        }
    }

    #中间件验证签名
    protected function checkSign($postData)
    {
        $param = $postData;
        $key   = '92ope08wh$@6Cfwf3jhgf7shvdYFWE24eh641d';
        $sign  = $param['sign'];
        unset($param['sign']);
        ksort($param);
        $paramStr = '';
        foreach ($param as $paramKey => $paramVal)
        {
            if(is_array($paramVal) || $paramVal === null || $paramVal === '')continue;
            $paramStr .= $paramKey.'='.$paramVal.'&';
        }
        $paramStr.='key='.$key;
        $newSign = md5(str_replace(['%21', '%2A', '%28', '%29', '+'], ['!', '*', '(', ')', '%20'],urlencode($paramStr)));
        if($newSign!=$sign) {
            \Log::out(json_encode($param, JSON_UNESCAPED_UNICODE), 'sign');
            throw new \Exception('异常请求', 30017);
        }
    }

    /**
     * @api 前端验证登陆标记token是否合法
     */
    protected function checkToken()
    {
        $token = getHeader('Authorization');
        if (empty($token)) {
            if (!$token = \Yaf_Dispatcher::getInstance()->getRequest()->get('Authorization')) {
                throw new \Exception('Authorization为空.', 401);
            }
        }
        $user = remember('auth_' . $token, -1, function () use ($token) {
            $user = \membersModel::where('token', $token)->first();
            if (empty($user)) {
                throw new \Exception('Authorization无效.', 401);
            }
            $data = [
                'user_id'  => $user->id,
                'nickname' => $user->nickname,
                'phone'    => $user->phone,
                'avatar'   => $user->avatar,
                'shop_id'  => $user->shop_id,
                'store_id' => $user->store_id,
            ];
            return $data;
        });
        if (!$user) {
            throw new \Exception('登陆失败.', 401);
        }
        return array_to_object($user);
    }

    /**
     * @api 前端验证登陆标记token是否合法
     */
    protected function checkWxToken($pageParam)
    {
        $token = $pageParam['token'];
        if (empty($token)) {
            throw new \Exception('token为空.', 403);
        }
        $user = remember('auth_' . $token, -1, function () use ($token) {
            $user = DB::table('customer')->where('token', $token)->first();
            if (empty($user)) {
                throw new \Exception('token无效.', 403);
            }
            $data = [
                'user_id'  => $user->id,
                'nickname' => $user->nickname,
                'phone'    => $user->phone,
                'avatar'   => $user->avatar,
            ];
            return $data;
        });
        if (!$user) {
            throw new \Exception('登陆失败.', 403);
        }
        return array_to_object($user);
    }

    /**
     * @api 前端验证签名是否合法
     */
    protected function checkPostSign($postData)
    {
        $params = $postData;
        \Log::out(json_encode($params), 'gate');
        $params['secretKey'] = DB::table('app')->where('appId', $params['appId'])->value('secretKey');
        $sign                = $params['sign'];
        foreach ($params as $k => $v) {
            if (!in_array($k, ['appId', 'secretKey', 'timestamp', 'carRfid', 'carPlate']) || $v === '') {
                unset($params[$k]);
            }
        }
        ksort($params);
        $mySign = sha1(http_build_query($params));
        if ($mySign !== $sign) {
            throw new \Exception('签名有误.', 403);
        }
        return true;
    }
}
